package com.gtlab1207.br_security.services;

import com.gtlab1207.br_security.common.CertUtil;
import com.gtlab1207.br_security.models.dao.CertDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyStore;
import java.security.cert.X509Certificate;
import java.util.Date;
import java.util.Enumeration;

import static com.gtlab1207.br_security.common.Util.delFolder;
import static com.gtlab1207.br_security.common.Util.deleteFile;

/**
 * 证书校验业务层 证书有效期校验 证书真伪校验
 * */
@Slf4j
@Service
public class CheckCertService {

    // 证书的存放路径
    String baseCertPath="/Users/shier/Documents/cert/rsa/";
    //String baseCertPath="C://Users//AceSpring//Desktop//cert//rsa//";

    /**
     * 证书校验功能
     * @param alias     用户的唯一标识
     * @param password  用户密码
     * @param certpath  用户上传的p12证书路径
     * @return          返回证书验证结果
     */
    public String CheckCert(String alias, String password, String certpath) throws IOException {

        String UserCert = baseCertPath + alias + "/" + alias + ".p12";
        //String UserCert = baseCertPath + alias + "//" + alias + ".p12";

        String upload = CertUtil.CheckP12(alias,password,certpath);

        String local = CertUtil.CheckP12(alias,password,UserCert);

        if(upload.equals(local)){
            // 校验相同之后 需要删除上传的证书
            String baseCertPath="/Users/shier/Documents/cert/rsa/uploaded/" + alias + ".p12"; //创建用户证书的目录
            deleteFile(baseCertPath);
            return local;
        }else {
            log.error("{} check error!",alias);
            return "error";
        }

    }
}
